package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
	"zy10/api/request"
	"zy10/consts"
	"zy10/internal/dao"
	"zy10/internal/model"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{

		Mobile: req.Mobile,
	}, &user)
	if user.Id == 0 {
		user = model.User{
			Mobile:   req.Mobile,
			Password: req.Password,
		}
		if !dao.Create(&user) {
			c.JSON(http.StatusOK, gin.H{
				"code": 1000,
				"msg":  "注册失败",
				"data": nil,
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "注册成功",
			"data": user,
		})

	} else {
		if user.Password != req.Password {
			c.JSON(http.StatusOK, gin.H{
				"code": 1000,
				"msg":  "密码错误",
				"data": nil,
			})
			return
		}
		j := jwt2.NewJWT(consts.JWT_SECRET_KEY)
		claims := jwt2.CustomClaims{
			ID: user.Id,

			StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().UnixMilli() + 3600},
		}
		token, err := j.CreateToken(claims)
		if err != nil {
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": map[string]interface{}{
				"token": token,
				"user":  user,
			},
		})

	}

}
